package gy.com.sansharescuesystem.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.HeatMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.WeightedLatLng;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import gy.com.sansharescuesystem.R;
import gy.com.sansharescuesystem.base.BaseFragment;
import gy.com.sansharescuesystem.callback.CountCallBack;
import gy.com.sansharescuesystem.entity.ClsRescueResBySnData;
import gy.com.sansharescuesystem.entity.CountBean;
import gy.com.sansharescuesystem.entity.HeatDataBean;
import gy.com.sansharescuesystem.entity.HeatTotalBean;
import gy.com.sansharescuesystem.modle.CountModel;
import gy.com.sansharescuesystem.modle.impl.CountModelImpl;
import gy.com.sansharescuesystem.utils.Constant;
import gy.com.sansharescuesystem.utils.MapUtil;
import gy.com.sansharescuesystem.utils.NetWorkUtils;
import gy.com.sansharescuesystem.utils.SharePreferenceUtils;
import gy.com.sansharescuesystem.utils.UIUtils;

/**
 * function:数据统计
 * author:zsf
 * time:2017.07.15
 */

public class CountFragment extends BaseFragment implements View.OnClickListener {
    //救援实施次数
    private TextView rescueNumTw;
    //救援成功率
    private TextView rescueSuccessRateTw;
    //平均救援时长（分钟）
    private TextView rescueAverageTimeTw;
    //平均接警时长（分钟）
    private TextView averageAarmTimeTw;
    private static final int ACCESS_SUCCESS = 0;
    private static final int ACCESS_ERROR = 1;
    //2d地图
    private ImageView twoDMapImgVw;
    //卫星图
    private ImageView satelliteMapImgVw;
    //多发地
    private ImageView frequentlyImgVw;
    //放大按钮
    private ImageView enlargeImgVw;
    //缩小按钮
    private ImageView narrowImgVw;
    //全局布局
    private View view;
    //2D图被选中
    private static final int FLAG_TWO_MAP_FOCUS = 100;
    //卫星图被选中
    private static final int FLAG_STATELLITE_FOCUS = 101;
    //热力图数据获取成功
    private static final int FLAG_HEATMAP_DATA_SUCCESS = 102;
    //热力图数据获取失败
    private static final int FLAG_HEATMAP_DATA_FAIL = 103;
    //热力图加载成功
    private static final int FLAG_HEATMAP_LOAD_SUCCESS = 104;
    //    private int mPage=1;
    //点击的焦点位置
    private int flag;
    //多发地未被选中
    private boolean isFrequentSelected = false;
    //是否首次点击过多发地成功获取数据
    private boolean isFirstFrequent = true;
    //多发地数据
    private List<HeatDataBean> frequentDataList;
    //百度地图
    private TextureMapView tmapView;
    private HeatMap heatmap;
    private LinearLayout baiMapLayout;
    private BaiduMap mBaiduMap;
    //广播
    private CountBroadcastReceiver countReceiver = new CountBroadcastReceiver();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ACCESS_SUCCESS:
                    CountBean countBean = (CountBean) msg.obj;
                    if (countBean.getFlag().equals("1")) {
                        CountBean.CountDataBean countDataBean = countBean.getCountDataBean();
                        rescueNumTw.setText(countDataBean.getAll());
                        rescueSuccessRateTw.setText(getSuccess(countDataBean.getAll(), countDataBean.getSuccess()));
                        rescueAverageTimeTw.setText(getTime(countDataBean.getHelp_avg()));
                        //平均接警时长
                        averageAarmTimeTw.setText(getTime(countDataBean.getGet_avg()));
                    } else if (countBean.getFlag().equals("0")) {
                        UIUtils.showToast(mActivity, "请求数据失败，请稍后重试！");
                    }


                    break;

                case ACCESS_ERROR:
                    UIUtils.showToast(mActivity, "请求数据异常，请稍后重试！");
                    break;

                case FLAG_HEATMAP_DATA_SUCCESS:
                    frequentDataList = ((HeatTotalBean) msg.obj).getData();
                    if(frequentDataList!=null) {
                        addHeatMap(frequentDataList);
                        isFirstFrequent = false;
                    }else{
                        UIUtils.showToast(mActivity, "请求数据异常，请稍后重试！");
                    }
                    break;
                case FLAG_HEATMAP_DATA_FAIL:
                    isFirstFrequent = true;
                    if (frequentDataList != null && frequentDataList.size() > 0) {
                        frequentDataList.clear();
                    }
                    UIUtils.showToast(mActivity, "热力图请求数据异常，请稍后重试！");

                    break;
                default:

                    break;


            }
        }
    };

    @Override
    protected View onCreateView(LayoutInflater inflater) {
        SDKInitializer.initialize(this.getContext().getApplicationContext());
        view = inflater.inflate(R.layout.fragment_count, null);
        Log.i("CountFragment","onCreateView");
        return view;
    }

    @Override
    protected void initView() {
        Log.i("CountFragment","initView");
        rescueNumTw = (TextView) findViewById(R.id.rescueNumTw);
        rescueSuccessRateTw = (TextView) findViewById(R.id.rescueSuccessRateTw);
        rescueAverageTimeTw = (TextView) findViewById(R.id.rescueAverageTimeTw);
        averageAarmTimeTw = (TextView) findViewById(R.id.averageAarmTimeTw);
        baiMapLayout = (LinearLayout) findViewById(R.id.baiMapLayout);
        twoDMapImgVw = (ImageView) findViewById(R.id.twoDImgVw);
        satelliteMapImgVw = (ImageView) findViewById(R.id.satelliteImgVw);
        frequentlyImgVw = (ImageView) findViewById(R.id.multipleImgVw);
        enlargeImgVw = (ImageView) findViewById(R.id.enlargeImgVw);
        //缩小按钮
        narrowImgVw = (ImageView) findViewById(R.id.narrowImgVw);

        //全局布局
        //隐藏缩放按钮，需动态添加地图组件
        BaiduMapOptions options = new BaiduMapOptions();
        options.zoomControlsEnabled(false);
        options.scaleControlEnabled(false);
        tmapView = new TextureMapView(mContext, options);
        mBaiduMap=tmapView.getMap();

        RelativeLayout.LayoutParams params_map = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        baiMapLayout.addView(tmapView, params_map);

        if (SharePreferenceUtils.getIntPerferences(this.getContext(), "MAP_BUTTON_FOCUS", 0) == FLAG_TWO_MAP_FOCUS) {
            twoDMapImgVw.setImageResource(R.drawable.two_map_selected);
            flag = FLAG_TWO_MAP_FOCUS;
            tmapView.getMap().setMapType(BaiduMap.MAP_TYPE_NORMAL);
        } else if (SharePreferenceUtils.getIntPerferences(this.getContext(), "MAP_BUTTON_FOCUS", 0) == FLAG_STATELLITE_FOCUS) {
            satelliteMapImgVw.setImageResource(R.drawable.satellite_selected);
            tmapView.getMap().setMapType(BaiduMap.MAP_TYPE_SATELLITE);
            flag = FLAG_STATELLITE_FOCUS;
        } else {
            twoDMapImgVw.setImageResource(R.drawable.two_map_selected);
            flag = FLAG_TWO_MAP_FOCUS;
        }
        if (SharePreferenceUtils.getBooleanPerferences(this.getContext(), "FREQUENT_BUTTON_FOCUS", false)) {
            frequentlyImgVw.setImageResource(R.drawable.multiple_selected);
            isFrequentSelected = true;
            getHeatMapData();
        }
        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.RESCUE_DESTROY);
        filter.addAction(Constant.RESCUE_PAUSE);
        filter.addAction(Constant.RESCUE_RESUME);
        filter.addAction(Constant.RESCUE_STOP);
        filter.addAction(Constant.TO_COUNT_PAGE);
        filter.addAction(Constant.TO_HISTORY_PAGE);
        filter.addAction(Constant.TO_RESCUE_PAGE);
        getActivity().registerReceiver(countReceiver, filter);

    }

    @Override
    protected void setWidgetListener() {
        twoDMapImgVw.setOnClickListener(this);
        satelliteMapImgVw.setOnClickListener(this);
        frequentlyImgVw.setOnClickListener(this);
        enlargeImgVw.setOnClickListener(this);
        narrowImgVw.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        Log.i("CountFragment","initData");
        if (NetWorkUtils.IsHaveInternet(this.getContext())) {
            CountModel countModel = new CountModelImpl();
            countModel.getData(new CountCallBack() {
                @Override
                public void onSuccess(Object countBean) {
                    Message message = handler.obtainMessage();
                    message.obj = countBean;
                    message.what = ACCESS_SUCCESS;
                    handler.sendMessage(message);
                }

                @Override
                public void onFailed() {
                    Message message = handler.obtainMessage();
                    message.what = ACCESS_SUCCESS;
                    handler.sendMessage(message);
                }
            });

        } else {
            rescueNumTw.setText("");
            rescueSuccessRateTw.setText("");
            rescueAverageTimeTw.setText("");
            averageAarmTimeTw.setText("");
        }

    }

    private void addHeatMap(final List<HeatDataBean> respData) {
        List<LatLng> points = new ArrayList<LatLng>();
        List<WeightedLatLng> weightedLatLngList = new ArrayList<WeightedLatLng>();
        for (int i = 0; i < respData.size(); i++) {
            LatLng latLng = new LatLng(Double.parseDouble(respData.get(i).getLat()),
                    Double.parseDouble(respData.get(i).getLng()));
            //权重
            double intensity = respData.get(i).getCount();
            weightedLatLngList.add(new WeightedLatLng(latLng, intensity));
            points.add(latLng);
        }
        heatmap = new HeatMap.Builder().weightedData(weightedLatLngList).build();
        mBaiduMap.addHeatMap(heatmap);

        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng p : points) {
            builder = builder.include(p);
        }
        //取热点区域中心点，放在地图中心
        double lat1=points.get(0).latitude;
        double lon1=points.get(0).longitude;
        double lat2=points.get(points.size()-1).latitude;
        double lon2=points.get(points.size()-1).longitude;
        //缩放级别
        float zoom= MapUtil.getZoom(MapUtil.getDistance(lat1,lon1,lat2,lon2));
        double centerLat=(lat1+lat2)/2;
        double centerLon=(lon1+lon2)/2;
        LatLng pointLatLng = new LatLng(centerLat,centerLon);
        MapStatus.Builder mapStatusBuilder = new MapStatus.Builder();
        mapStatusBuilder.target(pointLatLng).zoom(zoom);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatusBuilder.build()));
        Log.i("addHeatMap缩放级别", "zoom:"+mBaiduMap.getMapStatus().zoom + "");
        Point point = new Point();
        this.getActivity().getWindowManager().getDefaultDisplay().getSize(point);
        Log.i("设备分辨率", "the screen size is " + point.toString());
    }

    private void getHeatMapData() {
        if (NetWorkUtils.IsHaveInternet(this.getContext())) {
            CountModel countModel = new CountModelImpl();
            countModel.getHeatData(new CountCallBack() {
                @Override
                public void onSuccess(Object heatMapObj) {
                    Message message = handler.obtainMessage();
                    message.obj = heatMapObj;
                    message.what = FLAG_HEATMAP_DATA_SUCCESS;
                    handler.sendMessage(message);
                }

                @Override
                public void onFailed() {
                    Message message = handler.obtainMessage();
                    message.what = FLAG_HEATMAP_DATA_FAIL;
                    handler.sendMessage(message);
                }
            });

        } else {
            UIUtils.showToast(mActivity, "没有网络，请稍后重试！");
        }


    }

    /**
     * function:把秒数转为分钟数
     *
     * @param time
     * @return
     */
    private String getTime(String time) {
        if (time.contains(","))
            time = time.replace(",", "");
        float floatTime = Float.parseFloat(time);
        String conversionTime = new DecimalFormat("0.00").format(floatTime / 60);
        return conversionTime;
    }

    /**
     * function:计算救援成功率
     *
     * @param allNum
     * @param successNum
     * @return
     */
    private String getSuccess(String allNum, String successNum) {
        float allNumFloat = Float.parseFloat(allNum);
        float successNumFloat = Float.parseFloat(successNum);
        NumberFormat nft = NumberFormat.getPercentInstance();
        nft.setMinimumFractionDigits(1);
        String conversionRate = nft.format(successNumFloat / allNumFloat);
        return conversionRate;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.twoDImgVw:
                if (flag != FLAG_TWO_MAP_FOCUS) {
                    twoDMapImgVw.setImageResource(R.drawable.two_map_selected);
                    SharePreferenceUtils.setIntSave(this.getContext(), "MAP_BUTTON_FOCUS", FLAG_TWO_MAP_FOCUS);
                    satelliteMapImgVw.setImageResource(R.drawable.satellite_map);
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                    flag = FLAG_TWO_MAP_FOCUS;
                }
                break;
            case R.id.satelliteImgVw:
                if (flag != FLAG_STATELLITE_FOCUS) {
                    satelliteMapImgVw.setImageResource(R.drawable.satellite_selected);
                    SharePreferenceUtils.setIntSave(this.getContext(), "MAP_BUTTON_FOCUS", FLAG_STATELLITE_FOCUS);
                    twoDMapImgVw.setImageResource(R.drawable.two_map);
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                    flag = FLAG_STATELLITE_FOCUS;

                }
                break;
            case R.id.multipleImgVw:

                frequentlyImgVw.setImageResource(R.drawable.multiple_selected);
                if (!isFrequentSelected) {
                    frequentlyImgVw.setImageResource(R.drawable.multiple_selected);
                    isFrequentSelected = true;
                    SharePreferenceUtils.setBooleanSave(this.getContext(), "FREQUENT_BUTTON_FOCUS", isFrequentSelected);
                    if (isFirstFrequent) {
                        getHeatMapData();
                    } else {
                        if (frequentDataList != null && frequentDataList.size() > 0) {
                            isFirstFrequent = false;
                            addHeatMap(frequentDataList);
                        }
                    }
                } else {
                    isFrequentSelected = false;
                    SharePreferenceUtils.setBooleanSave(this.getContext(), "FREQUENT_BUTTON_FOCUS", isFrequentSelected);
                    frequentlyImgVw.setImageResource(R.drawable.multiple);
                    if (heatmap != null)
                        heatmap.removeHeatMap();
                }
                break;
            case R.id.enlargeImgVw:
                //放大一个级别
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomIn());
                break;
            case R.id.narrowImgVw:
                //缩小一个级别
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomOut());
                break;


        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }
    private int pageFlage = 3;
    class CountBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.RESCUE_PAUSE:
                    if (tmapView != null) {
                        tmapView.onPause();
                    }
                    break;
                case Constant.RESCUE_RESUME:

                    if(pageFlage==Constant.FLAG_COUNT) {
                        if (tmapView != null)
                            tmapView.onResume();
                    }
                    break;
                case Constant.RESCUE_STOP:
                    if(tmapView!=null)
                        tmapView.onPause();
                    break;
                case Constant.RESCUE_DESTROY:
                    if(tmapView!=null)
                        tmapView.onDestroy();
                    break;
                case Constant.TO_COUNT_PAGE:
                    pageFlage = intent.getIntExtra("flag", 0);
                    if (tmapView != null) {
                        tmapView.onResume();
                    }
                    break;
                case Constant.TO_HISTORY_PAGE:
                    pageFlage = intent.getIntExtra("flag", 0);
                    if (tmapView != null) {
                        tmapView.onPause();
                    }
                    break;
                case Constant.TO_RESCUE_PAGE:
                    pageFlage = intent.getIntExtra("flag", 0);
                    if (tmapView != null) {
                        tmapView.onPause();
                    }
                    break;
            }
        }
    }
}
